package com.fys.order.service.impl;

import com.fys.order.dataobject.OrderDetail;
import com.fys.order.dataobject.OrderMaster;
import com.fys.order.dto.OrderDTO;
import com.fys.order.enums.OrderStatusEnum;
import com.fys.order.enums.PayStatusEnum;
import com.fys.order.enums.ResultEnum;
import com.fys.order.exception.OrderException;
import com.fys.order.repository.OrderDetailRepository;
import com.fys.order.repository.OrderMasterRepository;
import com.fys.order.service.OrderService;
import com.fys.order.utils.KeyUtil;
import com.fys.product.client.ProductClient;
import com.fys.product.common.DecreaseStockInput;
import com.fys.product.common.ProductInfoOutput;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: fys
 * @description:
 * @create: 2020-07-24 10:45
 **/
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private ProductClient productClient;


    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        /**
         * 1. 参数检验
         * 2. 查询商品信息(调用商品服务)
         * 3. 计算总价(调用商品服务)
         * 4. 扣库存(调用商品服务)
         * 5. 订单入库
         */
        String orderId = KeyUtil.genUniqueKey();
        //查询商品信息(调用商品服务)
        List<String> productIdList = orderDTO.getOrderDetailList().stream().map(OrderDetail::getProductId).collect(Collectors.toList());
        List<ProductInfoOutput> productInfoOutputs = productClient.listForOrder(productIdList);

        //计算总价(调用商品服务)
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        BigDecimal orderAmout = new BigDecimal(BigInteger.ZERO);
        for(ProductInfoOutput productInfo:productInfoOutputs){
            for(OrderDetail orderDetail:orderDetailList){
                if(orderDetail.getProductId().equals(productInfo.getProductId())){
                    //总价 = 单价 * 数量
                    BigDecimal productPrice = productInfo.getProductPrice();
                    Integer productQuantity = orderDetail.getProductQuantity();
                    orderAmout = productPrice.multiply(new BigDecimal(productQuantity))
                            .add(orderAmout);
                    //订单详情入库
                    BeanUtils.copyProperties(productInfo, orderDetail);
                    orderDetail.setDetailId(KeyUtil.genUniqueKey());
                    orderDetail.setOrderId(orderId);
                    orderDetailRepository.save(orderDetail);
                }
            }
        }

        //扣库存(调用商品服务)
        List<DecreaseStockInput> decreaseStockInputList = orderDetailList.stream()
                .map(e -> new DecreaseStockInput(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.decreaseStock(decreaseStockInputList);

        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        // 唯一id的生成需要单独开个项目来生成
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmout);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        orderDTO.setOrderId(orderId);
        return orderDTO;
    }


    /**
    * @Description: 卖家访问：完成订单
    * @Date:   2020/8/13 17:07
    * @Author: fys
    */
    @Override
    @Transactional
    public OrderDTO finish(String orderId) {
        //1. 先查询订单
        Optional<OrderMaster> orderMasterOptional = orderMasterRepository.findById(orderId);
        if (!orderMasterOptional.isPresent()) {
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }

        //2. 判断订单状态
        OrderMaster orderMaster = orderMasterOptional.get();
        if (OrderStatusEnum.NEW.getCode() != orderMaster.getOrderStatus()) {
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //3. 修改订单状态为完结
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        orderMasterRepository.save(orderMaster);

        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new OrderException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

}
